const fs = require('fs').promises;
const path = require('path');
const vueCompiler = require('vue-template-compiler');
const parser = require("@babel/parser");
const traverse = require("@babel/traverse").default;
const generator = require("@babel/generator").default;




async function findVueFiles(dir, map) {
    // 读取目录中的所有文件和子目录
    const entries = await fs.readdir(dir, { withFileTypes: true });
    const vueReplaceFiles = [];
    // 遍历每个文件或子目录
    for (const entry of entries) {
        const fullPath = path.join(dir, entry.name);
        if (entry.isDirectory()) {
            // 如果是目录，递归查找  
            const nestedVueFiles = await findVueFiles(fullPath, map);
            // vueFiles.push(...nestedVueFiles);
        } else if (entry.name.endsWith('.vue')) {
            // 如果是.vue文件，添加到结果数组中  
            // vueFiles.push(fullPath);
            const found = await replaceApi(fullPath, map)
            found && vueReplaceFiles.push(fullPath);
        }
    }
    return vueReplaceFiles;
}

/** 处理vue文件中重复的api 替换成一个 */
async function replaceApi(filePath, map) {
    const fileContent = await fs.readFile(filePath, 'utf-8');
    const result = vueCompiler.parseComponent(fileContent/*, { pad: 'line' }*/);
    const scriptContent = result.script.content

    if (!scriptContent) return false

    let found = false
    const ast = parser.parse(scriptContent, {
        sourceType: "module",
        plugins: ['jsx']
    });
    traverse(ast, {
        // 遍历AST，查找重复的api调用
        MemberExpression(path) {
            // 检查是否为api.xxx的调用
            if (
                path.node.object.type === 'Identifier' &&
                path.node.object.name === 'api' &&
                path.node.property.type === 'Identifier'
            ) {
                const name = path.node.property.name;
                map.forEach((value, key) => {
                    if (key.includes(name) && name !== value) {
                        found = true
                        path.node.property.name = value;
                        console.log(`In ${filePath.slice(filePath.indexOf('/src'))},Found call api.${name} replaced to api.${value} success`);
                    }
                })

            }
        },

    })
    if (!found) return false

    // 将修改后的 JavaScript AST 转换为代码
    const modifiedScriptContent = generator(ast, {}).code;

    // 找到 <script> 标签的位置
    const scriptStartIndex = fileContent.indexOf('<script>') + '<script>'.length;
    const scriptEndIndex = fileContent.indexOf('</script>');

    // 替换 <script> 内容
    const modifiedFileContent =
        fileContent.substring(0, scriptStartIndex) +
        '\n' + // 确保添加一个换行符
        modifiedScriptContent +
        '\n' + // 确保添加一个换行符
        fileContent.substring(scriptEndIndex);


    // // 将修改后的内容写回到原始文件中
    await fs.writeFile(filePath, modifiedFileContent, 'utf-8');
    console.log(`File ${filePath} has been updated.`);
    return true
}

module.exports = { findVueFiles, replaceApi }